package ug.co.icom.kyazze.healthticket.mongoHQ;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import ug.co.icom.kyazze.healthticket.data.QueryBuilder;
import ug.co.icom.kyazze.healthticket.data.User;

public class MongoHQEmailSearch{

	static BasicDBObject user = null;
	static String OriginalObject = "";
	static String server_output = null;
	static String temp_output = null;
	static User userToSend;
	private Locale locale = Locale.getDefault();

	public User getUserDetailsFromEmail(String email) {
		try {
			QueryBuilder qb = new QueryBuilder();
			URL url = new URL(qb.buildEmailUrl(email));
			HttpURLConnection conn = (HttpURLConnection) url
					.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() > 205) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));

			//System.out.println("Output from Server .... \n");
			while ((temp_output = br.readLine()) != null) {
				server_output = temp_output;
			}

			// Remove square brackets
			OriginalObject = server_output.substring(1, server_output.length() - 1);

			Object o = com.mongodb.util.JSON.parse(OriginalObject);

			DBObject userObj = (DBObject) o;
			
			User temp = new User();

			temp.PhoneNumber = userObj.get("phonenumber").toString();
			temp.PassCode = userObj.get("passcode").toString();
			temp.FirstName = userObj.get("firstname").toString();
			temp.LastName = userObj.get("lastname").toString();
			temp.OtherNames = userObj.get("othernames").toString();
			temp.Address = userObj.get("address").toString();
			temp.BloodType = userObj.get("bloodtype").toString();
			temp.Female = Boolean.parseBoolean(userObj.get("female").toString());
			temp.DateOfBirth = getDateFromString(userObj.get("dateofbirth").toString());
			temp.Email = userObj.get("email").toString();
			
			userToSend = temp;

		}catch (Exception e) {
			e.printStackTrace();
		}

		return userToSend;
	}
	
	private Date getDateFromString(String dateReceived) {
		SimpleDateFormat  format = new SimpleDateFormat("dd-MM-yyyy", locale);  
		try {  
		    Date date = format.parse(dateReceived);  
		    return date;  
		} catch (Exception e) {  
		    return new Date();
		}
	}

}
